package com.firmail.gson.ext;


import com.google.gson.*;

import java.lang.reflect.Type;

public class IntegerDefaultAdapter implements JsonDeserializer<Integer> {
    @Override
    public Integer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {

        // 如果integer类型的字段，进行一次类型转换
        try {
            return Integer.parseInt(json.getAsString());
        } catch (NumberFormatException e) {
        }
        return -1;
    }

    public static void main(String[] args) {
        String json = "{name:listen,isVip:true,age:abc,money:1.0}";
        Gson gson =
                new GsonBuilder().registerTypeAdapter(int.class, new IntegerDefaultAdapter())
                        .create();
        Model model = gson.fromJson(json, Model.class);// age字段解析出来为-1
    }
    class Model {
        String name;
        boolean isVip;
        int age;
        float money;
    }
}
